<template>
  <el-dialog
    title="编辑地区"
    :visible.sync="editMapShow"
    :lock-scroll="false"
    @opened="handleOpened"
    close-on-press-escape
    v-dialogDrag
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-tabs
      class="tabHight"
      :tab-position="tabPosition"
      v-model="mapTabs"
      @tab-click="invalidateMap"
    >
      <el-tab-pane label="详情" name="first">
        <el-form
          :model="editMapData"
          :rules="rules"
          ref="editMapData"
          label-width="13%"
          class="demo-mapForm"
          size="mini"
        >
          <el-form-item label="Token:" prop="token">
            <el-input v-model="editMapData.token" disabled> </el-input>
          </el-form-item>
          <el-form-item label="名称:" prop="name">
            <el-input v-model="editMapData.name"> </el-input>
          </el-form-item>
        </el-form>

        <!-- 地图 -->
        <div>
          <div id="editMap" class="tabHight" v-init-screen-h="180"></div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="元数据" name="second">
        <div v-if="editMapShow">
          <metaData
            :editmetaData="editmetaData"
            :isedit="isedit"
            @sendmetaDatas="sendmetaData"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="cancel">取 消</el-button>
      <el-button size="mini" type="primary" @click="subMapForm('editMapData')"
        >确 定
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  initMap,
  addControlOptions,
  createIcon,
} from "../../utils/leaflet-map";
import icon from "@/icons/comm/marker-icon-2x-violet.png";
import metaData from "../opensite/metaData";
import { TOKEN_RULES } from "@/utils/local";
import { putZones } from "@/api/zones";
export default {
  components: { metaData },
  props: {
    editMapShow: {
      type: Boolean,
    },
    editMapData: {
      type: Object,
    },
  },
  data() {
    return {
      tabPosition: "left",
      mapTabs: "first",
      map: "",
      layer: "",
      editBounds: [], //经纬度
      mapEdit: [], //转换后数据
      rules: {
        token: TOKEN_RULES,
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "长度在 1 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      editmetaData: [],
      metaDataJson: {},
      isedit: true,
    };
  },
  watch: {},
  mounted() {},
  methods: {
    //弹窗关闭
    handleClose() {
      this.$emit("showEditMap", "false");
      if (this.map) {
        this.map.remove();
      }
      this.map = "";
    },
    cancel() {
      this.handleClose();
    },
    // 弹窗打开
    handleOpened() {
      this.load_Map_2();
      this.editmetaData = this.editMapData.metadata;
      console.log("弹窗加载后", this.editMapData);
    },
    // 初始化地图
    load_Map_2() {
      var that = this;
      that.editBounds = that.editMapData.bounds;
      var latlng = "";
      console.log("that.editBounds :>> ", that.editBounds);
      if (that.editBounds && that.editBounds.length) {
        latlng = {
          lat: that.editBounds[0].latitude,
          lng: that.editBounds[0].longitude,
        };
      }
      var map = initMap("editMap", latlng, 5);
      // addControlOptions(map, [
      //   "drawRectangle",
      //   "drawPolygon",
      //   "removalMode",
      //   "enable",
      //   "editMode",
      // ]);
      const options = [
        "drawRectangle",
        "drawPolygon",
        "removalMode",
        "enable",
        "editMode",
      ];
      map.pm.addControls({
        position: "topleft",
        drawPolygon: options.includes("drawPolygon"), // 添加绘制多边形
        drawMarker: options.includes("drawMarker"), //添加按钮以绘制标记
        drawCircleMarker: options.includes("drawCircleMarker"), //添加按钮以绘制圆形标记
        drawPolyline: options.includes("drawPolyline"), //添加按钮绘制线条
        drawRectangle: options.includes("drawRectangle"), //添加按钮绘制矩形
        drawCircle: options.includes("drawCircle"), //  添加按钮绘制圆圈
        editMode: options.includes("editMode"), //  添加按钮编辑多边形
        dragMode: options.includes("dragMode"), //   添加按钮拖动多边形
        cutPolygon: options.includes("cutPolygon"), // 添加一个按钮以删除图层里面的部分内容
        removalMode: options.includes("removalMode"), // 清除图层
      });

      // 设置绘制后的线条颜色等
      map.pm.setPathOptions({
        color: "orange",
        fillColor: "green",
        fillOpacity: 0.4,
      });
      map.pm.setLang("zh"); //设置语言  en, de, it, ru, ro, es, fr, pt_br, zh , nl

      if (that.editBounds != "{}") {
        // 转换数据格式
        var mapEdit1 = [];
        let ele = {};
        that.editBounds.forEach((item) => {
          var itemList = [item.latitude, item.longitude];
          mapEdit1.push(itemList);
        });
        var myIcon = createIcon(icon);
        that.layer = L.polygon(mapEdit1, {
          draggable: false,
          icon: myIcon,
        }).addTo(map);
        that.layer.on("pm:edit", (e) => {
          console.log("编辑区域", e);
          that.editBounds = [];
          let mapeditlist = that.layer._latlngs;
          let ele = {};
          if (mapeditlist.length) {
            mapeditlist[0].forEach((item) => {
              ele = {
                latitude: item.lat,
                longitude: item.lng,
              };
              that.editBounds.push(ele);
            });
          }

          // that.editBounds = that.layer._latlngs;
        });
      }

      map.on("pm:create", (e) => {
        if (that.layer) {
          map.removeLayer(that.layer); // 移除已有图层,限制只有一个marker
        }

        // 清空参数，只保留当前
        that.editBounds = [];
        // 转换数据格式
        that.layer = e.layer;
        let maplist = e.layer._latlngs;
        let ele = {};
        if (maplist.length) {
          maplist[0].forEach((item) => {
            ele = {
              latitude: item.lat,
              longitude: item.lng,
            };
            that.editBounds.push(ele);
          });
        }

        console.log("划区域", e);
      });
      // 站点地图编辑内删除区域
      map.on("pm:remove", (e) => {
        that.editBounds = [];
      });
      that.map = map;
    },
    //地图重新调整位置
    invalidateMap(tab) {
      if (tab.name == "first") {
        this.$nextTick(() => {
          this.map.invalidateSize(true);
        });
      }
    },
    //提交
    subMapForm(editMapData) {
      this.$refs[editMapData].validate((valid) => {
        if (valid) {
          let formData = {};
          formData = this.editMapData;
          formData.bounds = this.editBounds;
          putZones(formData, this.editMapData.token).then((res) => {
            this.$msg({
              type: "success",
              message: "操作成功!",
            });
            this.$emit("editMapList");
            this.handleClose();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    },
  },
};
</script>

<style scoped>
#editMap {
  width: 100%;
  overflow: hidden !important;
  z-index: 100;
}
</style>